package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    //根据用户名查用户信息
    @Override
    public User findByUsername(String username) {
        //1.根据用户名查询用户信息
        User user = userDao.findByUsername(username);

        if (user == null){
            return null;
        }
        Integer userId = user.getId();
        //2.根据用户id查询角色信息
        Set<Role> roles = roleDao.findByUserId(userId);
        if (roles.size()==0){
            return user;
        }
        //3.根据角色id查询权限信息
        for (Role role : roles) {
            Integer roleId = role.getId();
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            role.setPermissions(permissions);
        }
        user.setRoles(roles);

        return user;
    }

    //添加新的用户
    @Override
    public void addNewUser(User user, Integer[] roleIds) {

        //将密码进行 BCrypt 加密
        String password = user.getPassword();
        String hashpw = BCrypt.hashpw(password, BCrypt.gensalt());
        user.setPassword(hashpw);

        //添加新的用户表
        userDao.addNewUser(user);
        Integer userId = user.getId();
        //设置新的用户角色关联关系
        this.setNewUserAndRole(userId,roleIds);
    }

    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);
        Page<User> page = userDao.findByCondition(queryString);

        return new PageResult(page.getTotal(),page.getResult());
    }

    //第一次删除,可能有子关联
    @Override
    public Result deleteFirst(Integer id) {

        //根据用户id查询是否有关联数据
        Long count = userDao.findCountInUserAndRole(id);

        if (count>0){

            return new Result(true, MessageConstant.DELETE_USER_FAIL,"hasSon");
        }
        //删除用户
        userDao.deleteByUserId(id);

        return new Result(true, MessageConstant.DELETE_USER_SUCCESS,"N");
    }

    //第二次删除,包括子关联
    @Override
    public void deleteSecond(Integer id) {

        //根据用户id,删除关联数据
        userDao.deleteUserAndRole(id);

        //根据用户id,删除用户
        userDao.deleteByUserId(id);

    }

    //根据id查询用户信息
    public User findById(Integer id){

       return userDao.findById(id);
    }

    //根据用户id查询关联角色id集合
    @Override
    public List<Integer> findRoleIds(Integer userId) {

        return userDao.findRoleIds(userId);
    }

    //修改用户信息
    @Override
    public void editUser(User user, Integer[] roleIds) {

        //1.根据用户id更新用户基本信息
        userDao.updateUserById(user);

        Integer userId = user.getId();
        //2.根据用户id删除关联信息

        userDao.deleteUserAndRole(userId);

        //3.根据用户id和角色id集合添加新的关联关系
        this.setNewUserAndRole(userId,roleIds);


    }


    //设置新的用户角色关联关系
    public void setNewUserAndRole(Integer userId,Integer[] roleIds){

        if (roleIds != null&& roleIds.length > 0){
            for (Integer roleId : roleIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("userId",userId);
                map.put("roleId",roleId);
                userDao.addNewUserAndRole(map);
            }
        }
    }

}
